package com.ljt.yupictureddd.infrastracture.api.aliyunai;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ljt.yupictureddd.infrastracture.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.ljt.yupictureddd.infrastracture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.ljt.yupictureddd.infrastracture.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.ljt.yupictureddd.infrastracture.exception.BusinessException;
import com.ljt.yupictureddd.infrastracture.exception.ErrorCode;
import com.ljt.yupictureddd.infrastracture.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class AliYunAiApi {

    @Value("${aliYunAi.apiKey}")
    private String apiKey;

    public static final String CREATE_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    public static final String GET_OUT_PAINTING_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";

    /**
     * 发起扩图请求API
     *
     * @param createOutPaintingTaskRequest
     * @return
     */
    public  CreateOutPaintingTaskResponse createOutPaintingTaskRequest(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        ThrowUtils.throwIf(ObjUtil.isNull(createOutPaintingTaskRequest), ErrorCode.PARAMS_ERROR);
        // 发送post请求
        HttpRequest httpRequest = HttpRequest.post(CREATE_OUT_PAINTING_TASK_URL)
                .header("Authorization", "Bearer " + apiKey)
                .header("X-DashScope-Async", "enable")
                .header("Content-Type", "application/json")
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        // 处理响应
        try (HttpResponse response = httpRequest.execute()) {
            if (!response.isOk()) {
                log.error("请求异常,{}", response.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
            CreateOutPaintingTaskResponse createOutPaintingTaskResponse = JSONUtil.toBean(response.body(), CreateOutPaintingTaskResponse.class);
            if (createOutPaintingTaskResponse.getCode() != null) {
                String errorMessage = createOutPaintingTaskResponse.getMessage();
                log.error("请求异常：{}", errorMessage);
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "AI 扩图失败，" + errorMessage);
            }
            return createOutPaintingTaskResponse;
        }
    }

    /**
     * 查询ai扩图任务结果状态
     * @param taskId
     * @return
     */
    public  GetOutPaintingTaskResponse getOutPaintingTaskResponse(String taskId) {
        // curl -X GET \
        // --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
        // https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx
        // 发起请求
        HttpRequest httpRequest = HttpRequest.get(String.format(GET_OUT_PAINTING_TASK_URL, taskId))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json");
        // 处理响应
        try (HttpResponse response = httpRequest.execute()) {
            if (!response.isOk()) {
                log.error("请求异常,{}", response.body());
                throw new BusinessException(ErrorCode.OPERATION_ERROR);
            }
            return JSONUtil.toBean(response.body(), GetOutPaintingTaskResponse.class);
        }
    }

}
